package com.itheima.reggic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggic.common.CustomException;
import com.itheima.reggic.common.R;
import com.itheima.reggic.dto.SetmealDto;
import com.itheima.reggic.mapper.SetmealMapper;
import com.itheima.reggic.pojo.Setmeal;
import com.itheima.reggic.pojo.SetmealDish;
import com.itheima.reggic.service.SetmealDishService;
import com.itheima.reggic.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    @Transactional
    public void addWithDish(SetmealDto setmealDto) {
        // 直接保存套餐信息
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        // 保存套餐内的菜品信息
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void deleteWithDish(List<Long> ids) {
//        我的代码
//        //判断套餐是否已经停售
//        for (Long id : ids) {
//            Setmeal setmeal = this.getById(id);
//            if (setmeal == null)
//                throw new CustomException("套餐不存在!");
//            if (setmeal.getStatus() == 1) {
//                throw new CustomException("套餐未停售,请先停售!");
//            }
//            // 首先删除套餐内包含的菜品
//            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(SetmealDish::getSetmealId, id);
//            setmealDishService.remove(queryWrapper);
//            // 删除套餐数据
//            this.removeById(id);
//        }

//        视频中的代码
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper);
        if (count > 0)
            throw new CustomException("套餐未停售,请先停售!");

        // 删除关联在套餐中的菜品
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lambdaQueryWrapper);
        // 删除套餐本身数据
        this.removeByIds(ids);

    }
}
